package com.yong.common.permission;

import android.Manifest;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.tbruyelle.rxpermissions3.RxPermissions;
import com.yong.common.popup.PopupPermissionsMsg;
import com.yong.common.utils.ToastUtils;
import com.yong.common.utils.Utils;

/**
 * @version 1.0
 * @Description: 权限申请工具类
 * @Author: yong
 * @time 2021/8/7 0007 16:54
 */
public class PermissionUtil {

    /**
     * rxPermission请求权限
     *
     * @param target
     * @param permissions
     * @param permissionImpl
     */
    public static void rxRequest(Object target, String[] permissions, PermissionImpl permissionImpl) {
        RxPermissions rxPermission;
        if (target instanceof Fragment) {
            Fragment fragment = (Fragment) target;
            rxPermission = new RxPermissions(fragment);
        } else if (target instanceof FragmentActivity) {
            FragmentActivity activity = (FragmentActivity) target;
            rxPermission = new RxPermissions(activity);
        } else {
            try {
                ToastUtils.showLongToast(null,"页面异常");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            return;
        }

        //请求权限
        rxPermission
                .requestEachCombined(permissions)
                .subscribe(permission -> {
                    //如果所有权限都同意了
                    if (permission.granted) {
                        permissionImpl.onSuccess();
                        //至少有一个权限未同意
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        new PopupPermissionsMsg(Utils.getApp().getApplicationContext(), "你已拒绝" + permissionNameFormat(permission.name) + "权限，为了不影响使用，请尽量同意改权限。", true).showPopupWindow();
                        //禁止后不在访问
                    } else {
                        new PopupPermissionsMsg(Utils.getApp().getApplicationContext(), "该功能需要" + permissionNameFormat(permission.name) + "权限，你已选择禁止后不在访问，若想使用对应的功能，请手动去设置页面设置。").showPopupWindow();
                    }
                });
    }

    /**
     * 权限名格式化
     *
     * @param permissionName
     * @return
     */
    public static String permissionNameFormat(String permissionName) {
        return permissionName
                .replace(Manifest.permission.CAMERA, "相机")
                .replace(Manifest.permission.ACCESS_FINE_LOCATION, "定位")
                .replace(Manifest.permission.READ_EXTERNAL_STORAGE, "读")
                .replace(Manifest.permission.WRITE_EXTERNAL_STORAGE, "写");
    }

}
